# -*- encoding:utf-8 -*-
# @time: 2023/4/4 21:04
# @author: Maxs_hu
"""
如果想要以后使用分页，需要以下两个步骤：
在视图函数：
    def customer_list(request):
        keyword = request.GET.get('keyword', "")

        # 关键词查询
        # Q查询
        q = Q()
        if keyword:
            keyword = keyword.strip()
            q.connector = 'OR'
            q.children.append(('username__contains', keyword))
            q.children.append(('mobile__contains', keyword))
            q.children.append(('level__title__contains', keyword))  # __跨表查询
            q.children.append(('creator__username__contains', keyword))

        # 在html界面会存在跨表查询. 为了提升效率减少hit database次数加上select_related
        queryset = models.Customer.objects.filter(q).filter(active=1).select_related('level', 'creator')  # 加上foreign_key字段
        print(queryset.query)  # 当前查询的sql

        # 封装的分页对象
        pager = pagination(request, queryset)
        context = {
            'show_data': pager.show_data,
            'pager_string': pager.html(),
            'keyword': keyword
        }
        return render(request, 'customer_list.html', context)

在html页面上：
    {% for row in show_data %}
        {{row.id}}
        ...
    {% endfor %}

    <ul class="pagination">
        {{ pager_string }}
    </ul>
"""
import copy
from django.utils.safestring import mark_safe


class pagination:
    def __init__(self, request, queryset, per_page_count=10):
        self.request = request
        self.queryset = queryset
        self.per_page_count = per_page_count

        self.current_page = self.request.GET.get('page')
        # print(self.current_page)
        if self.current_page:
            if not self.current_page.isdigit():
                self.current_page = 1
        else:
            self.current_page = 1
        self.current_page = int(self.current_page)
        self.total_count = self.queryset.count()  # 总条数
        self.total_page, div = divmod(self.total_count, self.per_page_count)  # 每页条数
        if div:
            self.total_page += 1

        # 处理违法页数问题
        if self.current_page <= 0:
            self.current_page = 1
        if self.current_page > self.total_page:
            if self.total_page != 0:
                self.current_page = self.total_page  # 这里修改self.current_page的全局值. 而不是在单个方式中修改局部的值
        # print(self.current_page)

    def html(self):
        self.request.GET._mutable = True
        query_dict = copy.deepcopy(self.request.GET)  # 拷贝一份. 防止污染request的内容

        # 处理极限的问题
        # 1.当总页数不超过11页的时候
        if self.total_page <= 11:
            start = 1
            end = self.total_page
        # 2.当总页数大于11页的时候
        else:
            # 最小极限
            if self.current_page < 6:
                start = 1
                end = 11
            # 最大极限
            elif self.current_page > self.total_page - self.per_page_count / 2:
                start = self.total_page - 10
                end = self.total_page
            # 常规情况
            else:
                start = self.current_page - 5
                end = self.current_page + 5

        # 创建li标签
        li_list = []

        query_dict.setlist('page', [1])
        li_list.append('<li><a href="?{}">首页</a></li>'.format(query_dict.urlencode()))
        if self.current_page == 1:
            li_list.append('<li class="disabled"><a href="#">上一页</a></li>')
        else:
            query_dict.setlist('page', [self.current_page - 1])
            li_list.append('<li><a href="?{}">上一页</a></li>'.format(query_dict.urlencode()))
        for item in range(int(start), int(end + 1)):
            if item == self.current_page:
                query_dict.setlist('page', [item])
                li_tag = '<li class="active"><a href="?{}">{}</a></li>'.format(query_dict.urlencode(), item)
            else:
                query_dict.setlist('page', [item])
                li_tag = '<li><a href="?{}">{}</a></li>'.format(query_dict.urlencode(), item)
            li_list.append(li_tag)
        if self.current_page == self.total_page:
            li_list.append('<li class="disabled"><a href="#">下一页</a></li>')
        else:
            query_dict.setlist('page', [self.current_page + 1])
            li_list.append('<li><a href="?{}">下一页</a></li>'.format(query_dict.urlencode()))
        query_dict.setlist('page', [self.total_page])
        li_list.append('<li><a href="?{}">尾页</a></li>'.format(query_dict.urlencode()))
        li_list.append('<li class="disabled"><a href="#">共{}页 {}条数据</a></li>'.format(self.total_page, self.total_count))

        li_str = mark_safe("".join(li_list))
        return li_str

    @property
    def show_data(self):
        show_data = self.queryset[(self.current_page - 1) * self.per_page_count: self.current_page * self.per_page_count]
        # print(self.current_page)
        return show_data
